package cn.yywd_123;

import cn.yywd_123.biliarchiver.account.FavoriteLists;
import cn.yywd_123.biliarchiver.account.Session;
import cn.yywd_123.biliarchiver.utils.BiliVideo;
import cn.yywd_123.biliarchiver.utils.Downloader;
import cn.yywd_123.biliarchiver.utils.HttpsResponse;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
	public static final Path workDirectory = new File("").toPath().toAbsolutePath();
	static final Scanner stdin = new Scanner(System.in);

	public static void main(String[] args) {
		System.out.println("当前工作目录为" + workDirectory);

		Session.loadSession();

		System.out.println("(输入非选项值以返回哦)");

		while (true) {
			System.out.print("菜单\n" + "1.下载收藏夹\n" + "2.设置\n" + "3.关于\n> ");

			switch (stdin.nextLine()) {
				default:
				case "0":
					System.out.println("正在退出...");
					System.exit(0);
					break;
				case "1":
					download();
					break;
				case "2":
					setting();
					break;
				case "3":
					about();
					break;
			}
		}
	}

	static void download() {
		List<FavoriteLists.FavoriteList> favoriteLists = FavoriteLists.getLists(Session.current.getUserInfo().getMid());

		System.out.println("收藏夹列表");

		AtomicInteger i = new AtomicInteger();
		favoriteLists.forEach(favoriteList -> System.out.printf("%d. [%s](%d个视频)\n", i.incrementAndGet(), favoriteList.getTitle(), favoriteList.getMediaCount()));

		System.out.print("> ");

		int index;
		try {
			index = stdin.nextInt() - 1;
			if (index > favoriteLists.size()) throw new Exception();
		} catch (Exception e) {
			return;
		}

		FavoriteLists.FavoriteList list = favoriteLists.get(index);
		new File(workDirectory + "/out").mkdir();
		for (String bvid : list.getVideoBVIds()) {
			BiliVideo video = new BiliVideo(bvid);
			video.load();
			for (BiliVideo.Page page : video.getPages()) {
				JsonArray videoLinks = JsonParser.parseString(HttpsResponse.GET("https://api.bilibili.com/x/player/wbi/playurl?qn=80&bvid=" + video.getBvid() + "&cid=" + page.getCid())).getAsJsonObject().getAsJsonObject("data").getAsJsonArray("durl");

				try {
					Downloader.download(new URL(videoLinks.get(0).getAsJsonObject().get("url").getAsString()), new File(workDirectory + "/out/" + video.getBvid() + "_p" + page.getPageIndex() + ".mp4").toPath());
				} catch (MalformedURLException e) {
					throw new RuntimeException(e);
				}

				try {
					TimeUnit.SECONDS.sleep(1);
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
			}
		}
	}

	static void setting() {

	}

	static void about() {

	}
}